package com.jianyun.jyzs.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jianyun.jyzs.MainActivity;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.ThisApp;
import com.jianyun.jyzs.activity.AnnouncementActivity;
import com.jianyun.jyzs.activity.CrmActivity;
import com.jianyun.jyzs.activity.EngineeringDynamicActivity;
import com.jianyun.jyzs.activity.FlowExamineActivity;
import com.jianyun.jyzs.activity.FlowExamineHtmlActivity;
import com.jianyun.jyzs.activity.HtmlActivity;
import com.jianyun.jyzs.activity.NewCustomActivity;
import com.jianyun.jyzs.activity.SigninActivity;
import com.jianyun.jyzs.activity.WarningActivity;
import com.jianyun.jyzs.activity.newsign.NewSign2Activity;
import com.jianyun.jyzs.activity.newsign.NewSignActivity;
import com.jianyun.jyzs.adapter.OaCustomAdapter;
import com.jianyun.jyzs.base.MVPBaseFragment;
import com.jianyun.jyzs.bean.OaAppBean;
import com.jianyun.jyzs.bean.OaCustomBean;
import com.jianyun.jyzs.bean.TopBrodCastBean;
import com.jianyun.jyzs.common.CustomLinearLayoutManager;
import com.jianyun.jyzs.constant.SysConstant;
import com.jianyun.jyzs.dao.ItemModel;
import com.jianyun.jyzs.dao.ModelDao;
import com.jianyun.jyzs.db.EventCount;
import com.jianyun.jyzs.db.PushEvent;
import com.jianyun.jyzs.http.Api;
import com.jianyun.jyzs.http.RetrofitHelper;
import com.jianyun.jyzs.presenter.OaCustomPresenter;
import com.jianyun.jyzs.qrcode.IntentIntegrator;
import com.jianyun.jyzs.qrcode.barcodescanner.CaptureActivity;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.SPUtils;
import com.jianyun.jyzs.utils.Utils;
import com.jianyun.jyzs.view.custom.MyGridView;
import com.jianyun.jyzs.view.iview.IOaCustomView;
import com.jrmf360.rylib.common.util.ToastUtil;


import java.util.List;

import butterknife.BindView;
import io.rong.eventbus.EventBus;


/**
 * @author 杨仕俊
 * @description 应用界面自定义  图标和权限
 * Created by yangshijun on 2018/9/4.
 */

public class OaCustomFragment extends MVPBaseFragment<IOaCustomView, OaCustomPresenter>
        implements IOaCustomView {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private String userId;
    private OaCustomAdapter oaCustomAdapter;
    private List<OaAppBean> oaBeanList;
    private String enterpriseCode;
    private ModelDao dao;
    private TopBrodCastBean topBrodCastBean;
    public String help_url;
    private int flowSwtich;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected void initView() {

        oaCustomAdapter = new OaCustomAdapter(getActivity(), null, getActivity());
        oaCustomAdapter.setMyGridClickListener(new OaCustomAdapter.OnMyGridViewClickListener() {
            @Override
            public void onItemClick(int recyclerPostion, int myGridPositon) {
                OaAppBean.ItemBean itemBean = oaBeanList.get(recyclerPostion).getItems().get(myGridPositon);
                int enabled = itemBean.getEnabled();
                if (1 == enabled) {
                    String appType = itemBean.getAppType();
                    if (appType.equals("app")) {
                        startNative(itemBean.getAppInfo());
                    } else if (appType.equals("web")) {
                        startHtml(itemBean.getAppInfo(), itemBean.getAppName());
                    } else if (appType.equals("mainFrm")) {
                        startCustomActivity(itemBean);
                    }
                } else {
                    String appInfo = itemBean.getAppInfo();
                    if ("app_pm_engineering_dynamics".equals(appInfo) && "yuntechoa2".equals(enterpriseCode)) {
                        //工程动态
                        startActivity(new Intent(getActivity(), EngineeringDynamicActivity.class));
                    } else {
                        ToastUtil.showToast(getContext(), "权限未开放！");
                    }

                }

            }
        });
        oaCustomAdapter.setOnVpClickListener(new OaCustomAdapter.OnVpClickListener() {
            @Override
            public void onVpClick(int postion) {
                if (topBrodCastBean != null) {
                    String jumpUrl = topBrodCastBean.getList().get(postion).getJumpUrl();
                    Intent intent = new Intent(getActivity(), HtmlActivity.class);
                    intent.putExtra("urlUserHelper", jumpUrl);
                    startActivity(intent);
                }
            }
        });
        flowSwtich = LoginCache.getInstance().getFlowSwtich();

    }

    /**
     * 跳转应用扩展界面
     *
     * @param itemBean
     */
    private void startCustomActivity(OaAppBean.ItemBean itemBean) {
        Intent intent = new Intent(getActivity(), NewCustomActivity.class);
        intent.putExtra("itemBean", itemBean);
        startActivity(intent);
    }

    /**
     * 启动html跳转，加载webview
     *
     * @param appInfo
     */
    private void startHtml(String appInfo, String appName) {
        flowSwtich = LoginCache.getInstance().getFlowSwtich();


        switch (appName) {
            case "我的待办":
                Intent intent1 = new Intent(getActivity(), FlowExamineHtmlActivity.class);
                intent1.putExtra("url", appInfo);
                intent1.putExtra("isSercah", "1");
                startActivity(intent1);
                break;
            case "我的已办":
                Intent intent2 = new Intent(getActivity(), FlowExamineHtmlActivity.class);
                intent2.putExtra("url", appInfo);
                intent2.putExtra("isSercah", "1");
                startActivity(intent2);
                break;
            case "共享任务":
                Intent intent3 = new Intent(getActivity(), FlowExamineHtmlActivity.class);
                intent3.putExtra("url", appInfo);
                intent3.putExtra("isSercah", "1");
                startActivity(intent3);
                break;
            case "我的待办-分类":

                if (2 == flowSwtich) {
                    Intent intent4 = new Intent(getActivity(), FlowExamineHtmlActivity.class);
                    intent4.putExtra("isSercah", "0");
                    intent4.putExtra("url", appInfo);
                    //intent1.putExtra("appName", "1");
                    startActivity(intent4);
                } else {
//                    String urls = SysConstant.http_url_myWorkFlowUrl.replaceAll("\\{employeeid\\}", userId);
//                    intent4.putExtra("url", urls);
//                    intent4.putExtra("isSercah", "2");
//                    startActivity(intent4);
                    //移动审批
                    startActivity(new Intent(getActivity(), FlowExamineActivity.class));
                }
                break;
            case "我的已办-分类":
                Intent intent5 = new Intent(getActivity(), FlowExamineHtmlActivity.class);
                if (2 == flowSwtich) {
                    intent5.putExtra("url", appInfo);
                    intent5.putExtra("isSercah", "0");
                    startActivity(intent5);
                } else {
                  /*  String urls = SysConstant.http_url_workFlowUrl.replaceAll("\\{employeeid\\}", userId);
                    intent5.putExtra("url", urls);
                    intent5.putExtra("isSercah", "2");
                    startActivity(intent5);*/
                    //移动审批
                    startActivity(new Intent(getActivity(), FlowExamineActivity.class));
                }

                break;
            case "共享任务-分类":
                Intent intent6 = new Intent(getActivity(), FlowExamineHtmlActivity.class);
                if (2==flowSwtich){
                    intent6.putExtra("url", appInfo);
                    intent6.putExtra("isSercah", "0");
                    startActivity(intent6);
                }else {
                    /*String urls = SysConstant.http_url_shareWorkFlowUrl.replaceAll("\\{employeeid\\}", userId);
                    intent6.putExtra("url", urls);
                    intent6.putExtra("isSercah", "2");
                    startActivity(intent6);*/
                    //移动审批
                    startActivity(new Intent(getActivity(), FlowExamineActivity.class));
                }

                break;
            default:
                Intent intent7 = new Intent(getActivity(), HtmlActivity.class);
                if (appName.contains("请假")) {
                    intent7.putExtra("tag", "请假");
                }
                intent7.putExtra("url", appInfo);
                startActivity(intent7);
                break;
        }
    }

    /**
     * 启动本地跳转
     *
     * @param appInfo
     */
    private void startNative(String appInfo) {
        flowSwtich = LoginCache.getInstance().getFlowSwtich();
        switch (appInfo) {
            case "app_kq_sign":
                String version = LoginCache.getInstance().getSignVersion().getVersion();
                if ("1".equals(version)) {
                    //签到
                    startActivity(new Intent(getActivity(), NewSignActivity.class));
                } else if ("2".equals(version)) {
                    startActivity(new Intent(getActivity(), NewSign2Activity.class));
                } else if ("3".equals(version)) {
                    startActivity(new Intent(getActivity(), NewSignActivity.class));
                } else if ("4".equals(version)) {
                    startActivity(new Intent(getActivity(), NewSign2Activity.class));
                } else {
                    startActivity(new Intent(getActivity(), SigninActivity.class));
                }
                break;
            case "app_oa_news":
                //通知公告
                startActivity(new Intent(getActivity(), AnnouncementActivity.class));
                break;
            case "app_oa_crm":
                //CRM
                startActivity(new Intent(getActivity(), CrmActivity.class));
                //startActivity(new Intent(getActivity(), EngineeringDynamicActivity.class));
                break;
            case "app_common_scan":
                //扫一扫
                startActivityForResult(new Intent(getActivity(), CaptureActivity.class), IntentIntegrator.REQUEST_CODE);
                break;
            case "app_pm_engineering_dynamics":
                //工程动态
                startActivity(new Intent(getActivity(), EngineeringDynamicActivity.class));
                break;
            case "app_wf_approve":
                //移动审批
                Intent intent6 = new Intent(getActivity(), FlowExamineHtmlActivity.class);
                if (2==flowSwtich){
                    String urls = SysConstant.http_url_classWorkFlowUrl.replaceAll("\\{employeeid\\}", userId);
                    intent6.putExtra("url", urls);
                    intent6.putExtra("isSercah", "0");
                    startActivity(intent6);
                }else {
                    //移动审批
                    startActivity(new Intent(getActivity(), FlowExamineActivity.class));
                }
                break;
            case "app_earlywarning":
                //风险预警
                startActivity(new Intent(getActivity(), WarningActivity.class));
                break;

        }
    }

    @Override
    protected void initData() {
        recyclerView.setLayoutManager(new CustomLinearLayoutManager(getActivity(),
                LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(oaCustomAdapter);

        userId = LoginCache.getInstance().getUserInfo().getUserId();
        dao = new ModelDao(getActivity());
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();

        String appVserion = Utils.getVersionName(getActivity());
        getPresenter().getOaCustomIcon(userId, enterpriseCode, appVserion);
    }

    @Override
    protected int initContentLayout() {
        return R.layout.fragment_oa_custom;
    }

    @Override
    public OaCustomPresenter createPresenter() {
        return new OaCustomPresenter();
    }

    public void setWorkNum(int count) {
        oaCustomAdapter.setWorkFolowNum(count);
    }

    //出来evenbus收到的消息
    public void onEvent(final EventCount event) {
        ThisApp.applicationHandler.post(new Runnable() {
            @Override
            public void run() {
                int count = event.getCount();
                Log.i("test", "收到通知个数2：" + event.getCount());
                setWorkNum(count);
            }
        });
    }

    public void onEvent(PushEvent event) {
        if (event.getCategory() == 4) ThisApp.applicationHandler.post(new Runnable() {
            @Override
            public void run() {
                List<ItemModel> modelList = dao.getModelList(userId, enterpriseCode, 1);

            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        int count = (int) SPUtils.get(getActivity(), userId, 0);
        setWorkNum(count);
    }

    @Override
    public void onSuccess(OaCustomBean oaCustomBean) {

        help_url = oaCustomBean.getHelp_url();
        if (help_url == null || TextUtils.isEmpty(help_url)) {
            ongetListener.setView(false);
        } else {
            ongetListener.setView(true);
        }
        String topBroadcast = oaCustomBean.getTopBroadcast();
        if (topBroadcast != null && !TextUtils.isEmpty(topBroadcast)) {
            getPresenter().getTopCastBean(topBroadcast);
        }
        oaCustomAdapter.setBannerImg(topBroadcast);

        this.oaBeanList = oaCustomBean.getAppList();
        oaCustomAdapter.setOaBeanList(oaBeanList);

    }

    public interface OngetListener {
        void setView(Boolean isVisibility);
    }

    private OngetListener ongetListener;

    public void setOngetListener(OngetListener ongetListener) {
        this.ongetListener = ongetListener;
    }

    @Override
    public void onSuccess2(List<OaAppBean> oaBeanList) {
        this.oaBeanList = oaBeanList;
        oaCustomAdapter.setOaBeanList(oaBeanList);
    }

    @Override
    public void onGetTopCast(TopBrodCastBean topBrodCastBean) {
        this.topBrodCastBean = topBrodCastBean;
        if (topBrodCastBean.getResult()) {
            oaCustomAdapter.setTopBrodCast(topBrodCastBean.getList());
        }
    }

    @Override
    public void onFailed() {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == IntentIntegrator.REQUEST_CODE) {
            if (data != null) {
                String url = data.getStringExtra("url");
                if (url != null && !TextUtils.isEmpty(url)) {
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


}
